package org.tang.data;

import java.awt.Rectangle;
import java.awt.Robot;
import java.awt.Toolkit;
import java.awt.image.BufferedImage;
import java.io.File;
import java.util.Date;

import org.tang.data.common.Constant;

public class ScreenCapture {
	public ScreenCapture(String fileName) {
		try {
			Toolkit tk = Toolkit.getDefaultToolkit();
			tk.sync();
			// 创建屏幕高与宽区域
			Rectangle ecran = new Rectangle(tk.getScreenSize());
			Robot robot = new Robot();
			robot.setAutoDelay(0);
			robot.setAutoWaitForIdle(false);
			BufferedImage image = robot.createScreenCapture(ecran);
			File file = new File(fileName+".jpg");
			javax.imageio.ImageIO.write(image, "jpg", file);
		} catch (Exception e) {
			e.printStackTrace();
		}

	}

	private static String dir = null ;
	public static void main(String[] args) {
		String time = null;
		Date date = new Date();
		mkDir(date);
		long starTime = new Date(date.getYear(), date.getMonth(),
				date.getDate(), 9, 26, 0).getTime();
		long openTime = new Date(date.getYear(), date.getMonth(),
				date.getDate(), 9, 30, 0).getTime();
		long endTime = new Date(date.getYear(), date.getMonth(), date.getDate(),
				9, 40, 0).getTime();
		long current = System.currentTimeMillis();
		try {
			while (current < starTime) {

				Thread.sleep(20000);
				current = System.currentTimeMillis();
			}
			new ScreenCapture(dir + getString(current));
			while (true) {
				current = System.currentTimeMillis();
				if (current < openTime)
					Thread.sleep(5000);
				else if (current >= openTime
						&& current <= endTime) {
					new ScreenCapture(dir + getString(current));
					Thread.sleep(2000);
				}else
					break;

			}
		} catch (InterruptedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	private static void mkDir(Date date) {
		dir = new String(Constant.dirPre+"pic_"+date.getYear()%100 + "-" + change(date.getMonth()+1) + "-" + change(date.getDate()) + "\\");
		File file = new File(dir);
		if(!file.exists())
			file.mkdir();
	}

	private static String getString(long current) {
		Date tmp = new Date(current);
		return "" + tmp.getYear()%100 + "-" + change(tmp.getMonth()+1) + "-" + change(tmp.getDate())
				+ "-" + change(tmp.getHours()) + "_" + change(tmp.getMinutes()) + "_"
				+ change(tmp.getSeconds());
	}

	private static String change(int number) {
		if(number<10)
			return "0"+number;
		return ""+number;
	}

}